package com.shunwang.caipiao.data.container;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StatisticsNumberInterval {

	private List<StaticticsInterval> list = new ArrayList<StaticticsInterval>();
	
	public List<Integer> statistice(List<Integer> intervals,Integer top){
		if(intervals == null || top == null || top < 0){
			return null;
		}
		for(Integer num : intervals){
			hit(num);
		}
		Collections.sort(list);
		if(top > list.size()){
			throw new IllegalArgumentException("StatisticsNumberInterval top["+top+"] must not greate total num["+list.size()+"]");
		}
		List<Integer> number = new ArrayList<Integer>(top);
		for(int i=0;i<list.size();i++){
			StaticticsInterval interval = list.get(i);
			float avg = interval.getAvg();
			float val = interval.getMissTime() - avg;
			if(-1 < val && val < 1){
				number.add(list.get(i).getSource());
			}
			if(number.size() >= top){
				break;
			}
		}
		return number;
	}
	
	public void hit(Integer num){
		boolean findNot = true;
		for(StaticticsInterval interval : list){
			if(interval.getSource().equals(num)){
				findNot = false;
				interval.increment();
			}
			interval.miss();
		}
		if(findNot){
			list.add(new StaticticsInterval(num));
		}
	}
	
	private class StaticticsInterval implements Comparable{
		/** 原数据 */
		private Integer source;
		/** 平均值 */
		private float avg;
		/** 出现次数 */
		private Integer times=0;
		/** 未出现次数  */
		private Integer missTime=0;
		
		public StaticticsInterval(Integer source){
			this.source = source;
			this.times++;
		}
		
		public void increment(){
			this.times++;
			this.missTime=0;
		}
		
		public void miss(){
			this.missTime++;
		}
		

		public Integer getSource() {
			return source;
		}

		public float getAvg() {
			if(times ==0 || missTime ==0){
				return 0;
			}
			return new BigDecimal(times).divide(new BigDecimal(missTime),2,BigDecimal.ROUND_HALF_EVEN).floatValue();
		}

		public Integer getTimes() {
			return times;
		}

		public Integer getMissTime() {
			return missTime;
		}

		@Override
		public int hashCode() {
			return source;
		}

		@Override
		public boolean equals(Object obj) {
			return source.equals(obj);
		}

		@Override
		public int compareTo(Object o) {
			if(o instanceof StaticticsInterval){
				StaticticsInterval si = (StaticticsInterval)o;
				Integer target = si.getTimes().intValue();
				Integer src = this.getTimes().intValue();
				return target >= src? 1 : target == src? 0:-1;
			}
			throw new IllegalArgumentException("compare not instanceof StaticticsInterval,obj clazz:"+o.getClass().toString());
		}
		
		
		
		
	}
}
